
import allFilds, {filds, oprateButtons, fildsString} from 'common/filds'

export function getFormConfig(_row={}, formStore){
  const {lib, CLOUD_COLLECTION} = ao2
  const CUR_CLOUD_COLLECTION = CLOUD_COLLECTION || {}

  try {
    let row = Object.assign({}, _row)
    let columnsName = row.columnsName
    let collectionName = row.collectionName
    let globalCloudCollection = window.globalCloudCollection
    let columnsFilds = row.columnsFilds
    let buttons = oprateButtons[collectionName] || oprateButtons['default']
    if (globalCloudCollection[collectionName] && globalCloudCollection[collectionName].filds) {
      columnsFilds = globalCloudCollection[collectionName].filds
    } else {
      if (collectionName === 'CLOUD-TABLE-MANAGER') {
        columnsFilds = allFilds[collectionName]
      }
    }

    let myFilds = []
    if (columnsFilds) {
      if (lib.isString(columnsFilds)) {
        myFilds = eval(columnsFilds)
      } else {
        myFilds = columnsFilds
      }
      myFilds = myFilds.concat(buttons)
    } else {
      throw new Error(`没有为当前集合指定适配的表格配置(bootstrap table)`)
    }

    
    const formConfig = []
    let   methods = {}
    myFilds.forEach(fild => {
      for (const [key, value] of Object.entries(fild)) {
        if (key === 'methods') {
          methods = Object.assign({}, value)
        } else {
          const title = value.title
          let   input = value.input
          let   $input = null
          if (input) {
            if (typeof input === 'function') {
              input = input(row, formStore, CUR_CLOUD_COLLECTION)
            }

            if (lib.isArray(input)) {
              $input = input.filter(ipt=>{
                if (lib.isPlainObject(ipt)) {
                  let $ipt = Object.assign({}, ipt)
                  if (!$ipt.id) $ipt.id = key+'-'+lib.uuid(6)
                  return $ipt
                }
              })
            } else {
              $input = Object.assign({}, input)
              if (!$input.id) $input.id = key+'-'+lib.uuid(6)
              $input.value = row[key]||input.value||''
            }

            formConfig.push({
              title: ($input.title||title), 
              input: $input
            })
          }
        }
      }
    })
    return [formConfig, methods]
  } catch (error) {
    console.error(error);
  }
  
}